package cn.hyh.core.controller;

import cn.hyh.core.component.CanTellUserException;
import cn.hyh.core.costant.CustomKey;
import cn.hyh.core.pojo.User;
import cn.hyh.core.service.ServiceInterface.BlogService;
import cn.hyh.core.service.ServiceInterface.UserService;
import cn.hyh.core.util.DES;
import cn.hyh.core.vo.BlogInfoModel;
import cn.hyh.core.vo.LoginModel;

import cn.hyh.core.vo.ResultVo;
import com.alibaba.fastjson.JSON;
import lombok.experimental.Accessors;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.security.auth.spi.LoginModule;
import java.util.Map;

/**
 * @auther :hyh
 * @desc :    改接口需要进行登录操作 才能访问
 * @date :2019/7/23
 */
@RestController
public class WriteController {

    @Autowired
    private UserService userService;

    @Autowired
    private BlogService blogService;

   @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Map<String,Object>  login(@RequestBody LoginModel loginModel){

       String value = loginModel.getValue();
       if (StringUtils.isBlank(value)) {
           throw new CanTellUserException("请求参数为空！");
       }
       String decrypt = DES.decrypt(value, CustomKey.DEKEY);

       LoginModel model = JSON.parseObject(decrypt, LoginModel.class);
       String username = model.getUsername();
       String password = model.getPassword();
       if (StringUtils.isEmpty(username)) {
           throw new CanTellUserException("用户名不能空!");
       }
       if (StringUtils.isEmpty(password)) {
           throw new CanTellUserException("请输入密码!");
       }

       Map<String, Object> map = userService.login(username, password);

       return ResultVo.successResult(map);

   }


    @RequestMapping(value = "/validateLogin")
    public Map<String,Object>   validateLogin() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            User user = (User) subject.getSession().getAttribute("user");
            return ResultVo.successResult(user);
        }
        return ResultVo.failResultMsg("请先登录!");
    }

    @RequestMapping(value = "/write/writeBlog",method = RequestMethod.POST)
    public  Map<String,Object>  writeBlog(@RequestBody BlogInfoModel model) {
        blogService.writeBlog(model);
       return  ResultVo.successResult("发布成功!");
    }

}
